package info.xingxingdd.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import info.xingxingdd.admin.common.PageQuery;
import info.xingxingdd.admin.common.Result;
import info.xingxingdd.admin.entity.FileInfo;
import info.xingxingdd.admin.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 文件信息控制器
 */
@RestController
@RequestMapping("/api/file")
public class FileInfoController {
    
    @Autowired
    private FileInfoService fileInfoService;
    
    /**
     * 分页查询
     */
    @PostMapping("/page")
    public Result<IPage<FileInfo>> page(@RequestBody PageQuery query) {
        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();
        
        // 关键字查询
        if (StringUtils.hasText(query.getKeyword())) {
            wrapper.like(FileInfo::getFileName, query.getKeyword())
                   .or()
                   .like(FileInfo::getFileKey, query.getKeyword());
        }
        
        // 按创建时间倒序排序
        wrapper.orderByDesc(FileInfo::getCreateAt);
        
        Page<FileInfo> page = new Page<>(query.getCurrent(), query.getSize());
        IPage<FileInfo> result = fileInfoService.page(page, wrapper);
        
        return Result.success(result);
    }
    
    /**
     * 查询所有
     */
    @GetMapping("/list")
    public Result<List<FileInfo>> list() {
        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(FileInfo::getCreateAt);
        List<FileInfo> list = fileInfoService.list(wrapper);
        return Result.success(list);
    }
    
    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result<FileInfo> getById(@PathVariable Integer id) {
        FileInfo fileInfo = fileInfoService.getById(id);
        return Result.success(fileInfo);
    }
    
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<FileInfo> upload(@RequestParam("file") MultipartFile file, 
                                  @RequestParam(value = "remark", required = false) String remark) {
        try {
            FileInfo fileInfo = fileInfoService.uploadFile(file, remark);
            return Result.success(fileInfo);
        } catch (IOException e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载文件
     */
    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> download(@PathVariable Integer id) {
        FileInfo fileInfo = fileInfoService.getById(id);
        if (fileInfo == null) {
            return ResponseEntity.notFound().build();
        }
        
        File file = new File(fileInfo.getFilePath());
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        
        Resource resource = new FileSystemResource(file);
        String encodedFileName = URLEncoder.encode(fileInfo.getFileName(), StandardCharsets.UTF_8)
                .replace("+", "%20");
        
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName)
                .body(resource);
    }
    
    /**
     * 修改文件信息
     */
    @PutMapping
    public Result<FileInfo> update(@RequestBody FileInfo fileInfo) {
        // 设置更新时间
        fileInfo.setUpdateAt(LocalDateTime.now());
        
        fileInfoService.updateById(fileInfo);
        return Result.success(fileInfo);
    }
    
    /**
     * 删除文件
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Integer id) {
        boolean success = fileInfoService.deleteFile(id);
        if (success) {
            return Result.success();
        } else {
            return Result.error("文件删除失败");
        }
    }
} 